#!/usr/bin/env
import sys

__author__ = 'Gordon Sun'

'''
This file contains functions for formatting data structures.
'''

# function to print a 2d list in terminal
# I:  array to be printed <list>
# O:  field width or longest item length in the array
def print_2d_list(a):
    '''prints a 2D list in 2D form in the console'''
    if a == []:
        # So we don't crash accessing a[0]
        print []
        return
    rows, cols = len(a), len(a[0])
    field_width = max_item_length(a)
    print "[ ",
    for row in xrange(rows):
        if row > 0: print "\n  ",
        print "[ ",
        for col in xrange(cols):
            if col > 0: print ",",
            # The next 2 lines print a[row][col] with the given field_width
            formatted_array = "%" + str(field_width) + "s"
            print formatted_array % str(a[row][col]),
        print "]",
    print "]"


# function to help 2d list print; determines field width
# I:  array to be printed <list>
# O:  field width or longest item length in the array
def max_item_length(a):
    '''returns the longest element length in the array'''
    max_len, rows, cols = 0, len(a), len(a[0])
    for row in xrange(rows):
        for col in xrange(cols):
            max_len = max(max_len, len(str(a[row][col])))
    return max_len


# Takes in a list whatever it is and lowercases everything in it
# I: <list> or <string> format, no tuples)
# O: lowercased library <list>
def format_lib(library):
    '''Lowercases everything in a string list'''
    return [i.lower() for i in library]


# Takes in a file and converts it to a 2D list
# I: filename <string>
# O: outputs 2d <list> of <lists>
def read_table(filename):
    '''Takes in a file and converts it to a 2D list'''
    try:
        f = open(filename, 'r')
        data = f.readlines()
        file_contents = []
        for i, item in enumerate(data):
            row_n = (format_lib(data[i].rstrip('\n').split()))
            file_contents.append(row_n)
        return file_contents
    except IOError:
        print('Error opening the file - file does not exist')
        sys.exit()


# function takes in a filename that contains the codon table of frequencies for an organism and sorts it by codon
# I: Filename <string>
# O: <list> containing codon frequencies, codons, aa, and /10000
def process_org_codon_table(filename):
    '''processes organism codon frequency file and outputs the contents'''
    file_contents = sorted(read_table(filename), key=lambda x: x[0])
    return file_contents


# function turns a single element aray into a string ['a']->'a'
# I: <list> to be formatted
# O: <str> output
def array2str(list_input):
    return str(list_input[0])


# function turns a single element aray into a string ['1']->1
# I: <list> to be formatted
# O: <int> output
def array2int(list_input):
    return int(list_input[0])


# function flips a word backwards
# I: <str> word
# O: <str> drow
def flipflop(word):
    new_word = ''
    for x in reversed(xrange(len(word))):
        new_word += word[x]
    return new_word


# function removes a character from the word.
# I: <str> word to be modified, and <char> to be removed
# O: <str> new word without any char
def remove_str_annotation(word, remove_char):
    newword = ''
    for x in xrange(len(word)):
        if word[x] != remove_char:
            newword += word[x]
    return newword
